package com.yhq.yhqproject.base.modules.base.service;

import com.yhq.yhqproject.base.common.web.ListByPageResp;
import com.yhq.yhqproject.base.modules.base.entity.ErrorLog;
import com.yhq.yhqproject.base.modules.board.entity.dto.ListLogReq;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ErrorLogService {
    @Resource
    private MongoTemplate mongoTemplate;

    public ListByPageResp<ErrorLog> list(ListLogReq req) {
        Criteria criteria = null;
        if (req.getMd5() != null && req.getMd5().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("className").regex(req.getMd5());
            } else {
                criteria = criteria.and("className").regex(req.getMd5());
            }
        }
        if (req.getTitle() != null && req.getTitle().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("message").regex(req.getTitle());
            } else {
                criteria = criteria.and("message").regex(req.getTitle());
            }
        }

        Query query = new Query();
        if (criteria != null) {
            query = new Query(criteria);
        }

        long all = mongoTemplate.count(query, ErrorLog.class);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        query.skip((req.getPage() - 1) * req.getSize());
        query.limit(req.getSize());
        List<ErrorLog> list = mongoTemplate.find(query, ErrorLog.class);
        //
        ListByPageResp<ErrorLog> resp = new ListByPageResp<>();
        resp.setData(list);
        resp.setTotal(all);
        resp.setPage(req.getPage());
        resp.setSize(req.getSize());
        return resp;
    }

    public void delete3DayAgo(){
        Long end = System.currentTimeMillis() - 3 * 24 * 3600 * 1000;
        Query query = new Query(Criteria.where("createTime").lt(end));
        mongoTemplate.remove(query, ErrorLog.class);
    }
}
